package edu.whu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.whu.bean.User;
import edu.whu.dao.UserDao;
import edu.whu.exception.RegisterException;
import edu.whu.exception.UnregisterException;
import edu.whu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao dao;

    @Override
    public void register(User user) throws RegisterException {
        if (user == null || user.getId() == null || user.getName() == null){
            throw new RegisterException("用户或用户字段不能为空！");
        }
        dao.insert(user);
    }

    @Override
    public void unregister(User user) throws UnregisterException {
        if(dao.deleteById(user.getId()) == 0){
            throw new UnregisterException("用户ID不存在");
        }
    }

    @Override
    public List<User> selectAll() {
        return dao.selectList(new QueryWrapper<>());
    }

    @Override
    public User selectById(int id) {
        return dao.selectById(id);
    }

    @Override
    public List<User> selectByName(String name) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getName,name);
        return dao.selectList(wrapper);
    }
}
